package com.pai4j.zwiki.controller;

import com.pai4j.zwiki.domain.entity.ZWikiTaskQueueEntity;
import com.pai4j.zwiki.dto.ProjectAnalysisResponse;
import com.pai4j.zwiki.dto.ProjectSubmitRequest;
import com.pai4j.zwiki.service.ProjectAnalysisService;
import com.pai4j.zwiki.service.ZWikiTaskQueueService;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目分析控制器
 * 处理项目提交和分析相关的HTTP请求（已集成任务队列机制）
 *
 * @author pai4j
 * @since 2025-10-12
 * @updated 2025-10-14 集成任务队列和消息通知
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/analysis")
@RequiredArgsConstructor
public class ProjectAnalysisController {

    private final ProjectAnalysisService projectAnalysisService;
    private final ZWikiTaskQueueService taskQueueService;
    
    // 响应代码常量
    private static final String CODE_SUCCESS = "0";
    private static final String CODE_NOT_FOUND = "404";
    private static final String CODE_ERROR = "500";

    /**
     * 提交GitHub项目分析（使用任务队列）
     */
    @PostMapping("/submit/github")
    public ResponseEntity<Map<String, Object>> submitGitHubProject(
            @Valid @RequestBody ProjectSubmitRequest request) {
        
        log.info("收到GitHub项目提交请求（队列模式）: {}", request.getRepositoryUrl());
        
        try {
            // 提交到任务队列
            String taskId = taskQueueService.submitProjectAnalysisTask(request, null);
            
            // 查询队列状态
            ZWikiTaskQueueEntity taskQueue = taskQueueService.getTaskQueueStatus(taskId);
            Long queueSize = taskQueueService.getUserTaskQueue(request.getUserId()).stream()
                    .filter(t -> "pending".equals(t.getStatus()) || "processing".equals(t.getStatus()))
                    .count();
            
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("taskId", taskId);
            responseData.put("status", "queued");
            responseData.put("queuePosition", queueSize.intValue());
            responseData.put("message", "任务已加入队列，正在排队处理");
            
            return buildSuccessResponse("任务已加入队列", responseData);
            
        } catch (IllegalArgumentException e) {
            log.warn("GitHub项目提交参数错误: {}", e.getMessage());
            return buildErrorResponse(CODE_ERROR, "参数错误: " + e.getMessage(), 
                HttpStatus.BAD_REQUEST);
                
        } catch (Exception e) {
            log.error("提交GitHub项目失败", e);
            return buildErrorResponse(CODE_ERROR, "任务提交失败: " + e.getMessage(), 
                HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 提交ZIP项目分析（使用任务队列）
     */
    @PostMapping("/submit/zip")
    public ResponseEntity<Map<String, Object>> submitZipProject(
            @Valid @ModelAttribute ProjectSubmitRequest request,
            @RequestParam("file") MultipartFile file) {
        
        log.info("收到ZIP项目提交请求（队列模式）: {}, 文件大小: {} bytes", 
            request.getProjectName(), file != null ? file.getSize() : 0);
        
        try {
            // 提交到任务队列（包含ZIP文件）
            String taskId = taskQueueService.submitProjectAnalysisTask(request, file);
            
            ZWikiTaskQueueEntity taskQueue = taskQueueService.getTaskQueueStatus(taskId);
            Long queueSize = taskQueueService.getUserTaskQueue(request.getUserId()).stream()
                    .filter(t -> "pending".equals(t.getStatus()) || "processing".equals(t.getStatus()))
                    .count();
            
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("taskId", taskId);
            responseData.put("status", "queued");
            responseData.put("queuePosition", queueSize.intValue());
            responseData.put("message", "任务已加入队列，正在排队处理");
            
            return buildSuccessResponse("任务已加入队列", responseData);
            
        } catch (IllegalArgumentException e) {
            log.warn("ZIP项目提交参数错误: {}", e.getMessage());
            return buildErrorResponse(CODE_ERROR, "参数错误: " + e.getMessage(), 
                HttpStatus.BAD_REQUEST);
                
        } catch (Exception e) {
            log.error("提交ZIP项目失败", e);
            return buildErrorResponse(CODE_ERROR, "任务提交失败: " + e.getMessage(), 
                HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 查询分析任务状态
     */
    @GetMapping("/status/{taskId}")
    public ResponseEntity<Map<String, Object>> getAnalysisStatus(@PathVariable String taskId) {
        log.info("查询分析任务状态: {}", taskId);
        
        // 参数校验
        if (taskId == null || taskId.trim().isEmpty()) {
            return buildErrorResponse(CODE_ERROR, "任务ID不能为空", HttpStatus.BAD_REQUEST);
        }
        
        try {
            ProjectAnalysisResponse response = projectAnalysisService.getAnalysisStatus(taskId);
            return buildSuccessResponse("查询成功", response);
            
        } catch (Exception e) {
            log.warn("查询任务状态失败: {}", taskId, e);
            return buildErrorResponse(CODE_NOT_FOUND, "任务不存在", HttpStatus.NOT_FOUND);
        }
    }

    /**
     * 查询用户的分析任务列表
     */
    @GetMapping("/list/{userId}")
    public ResponseEntity<Map<String, Object>> getUserAnalysisList(@PathVariable Long userId) {
        log.info("查询用户分析任务列表: {}", userId);
        
        // 参数校验
        if (userId == null || userId <= 0) {
            return buildErrorResponse(CODE_ERROR, "用户ID无效", HttpStatus.BAD_REQUEST);
        }
        
        try {
            List<ProjectAnalysisResponse> list = projectAnalysisService.getUserAnalysisList(userId);
            return buildSuccessResponse("查询成功", list);
            
        } catch (Exception e) {
            log.error("查询用户任务列表失败: {}", userId, e);
            return buildErrorResponse(CODE_ERROR, "查询失败: " + e.getMessage(), 
                HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    
    // ========== 辅助方法 - 统一响应构建 ==========
    
    /**
     * 构建成功响应（消除代码重复）
     */
    private ResponseEntity<Map<String, Object>> buildSuccessResponse(String message, Object data) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", CODE_SUCCESS);
        result.put("message", message);
        result.put("data", data);
        return ResponseEntity.ok(result);
    }
    
    /**
     * 构建错误响应（消除代码重复）
     */
    private ResponseEntity<Map<String, Object>> buildErrorResponse(String code, String message, HttpStatus status) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", code);
        result.put("message", message);
        return ResponseEntity.status(status).body(result);
    }
}

